
package program;

import avenue.MyWindowEvent;
import avenue.Session;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.Card;
import model.DBManager;
import model.Program;
import model.ProgramRate;
import model.Station;
import model.VehicleCategory;

/**
 *
 * @author Team-2
 */
public class ListProgramForm extends javax.swing.JFrame {
    
    /**
     * Creates new form ListProgramForm
     */
    public ListProgramForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        initComponents();
        
        //Apply login user permissions
        addButton.setEnabled(Session.doesSessionUserHasPermissionType(
                                 Session.PROGRAMS_MODULE, Session.CAN_CREATE));
        editButton.setEnabled(Session.doesSessionUserHasPermissionType(
                                 Session.PROGRAMS_MODULE, Session.CAN_UPDATE));
        deleteButton.setEnabled(Session.doesSessionUserHasPermissionType(
                                 Session.PROGRAMS_MODULE, Session.CAN_DELETE));          
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        programQuer = java.beans.Beans.isDesignTime() ? null : em.createQuery("select p from Program p");
        programLlist = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(programQuer.getResultList());
        stationQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select s from Station s");
        stationList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(stationQuery.getResultList());
        vehicleCategoryQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select vc from VehicleCategory vc");
        vehicleCategpryList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(vehicleCategoryQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        jProgramsTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        addButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Προγράμματα");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, programLlist, jProgramsTable, "Πρόγραμμα");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        columnBinding.setColumnName("Πρόγραμμα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Περιγραφή");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(jProgramsTable);

        jLabel1.setText("Προγράμματα");

        addButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        addButton.setText("Νέο");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        deleteButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteButton.setText("Διαγραφή");
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editButton.setText("Επεξεργασία");
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Άκυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(addButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(deleteButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(editButton)))
                        .addGap(0, 127, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addButton)
                    .addComponent(deleteButton)
                    .addComponent(editButton))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed

       p = new Program();
       em.persist(p);
       List<ProgramRate> prl = p.getProgramRateList();
       if (prl==null){
           prl = new ArrayList<ProgramRate>();
           p.setProgramRateList(prl);
       }
       for (Station s: stationList){
           for (VehicleCategory vc: vehicleCategpryList){
               ProgramRate pr = new ProgramRate();
               pr.setCategoryId(vc);
               pr.setStationId(s);
               pr.setProgramId(p);
               em.persist(pr);
               p.getProgramRateList().add(pr);
           }
       }
      
       EditProgramForm epf = new EditProgramForm(p,false);       
       epf.setIconImage(Toolkit.getDefaultToolkit().getImage(Session.imgPath + "programmsIcon.png"));
       epf.setVisible(true);
       epf.setLocationRelativeTo(null); //center form    
       thisFrame=this;
       thisFrame.setEnabled(false);
///////////////////////////Start Listeners//////////////////////////////////////  
        epf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                    
                    
                    programLlist.add(p);
                    int row = programLlist.size() - 1;
        
                    jProgramsTable.setRowSelectionInterval(row, row);
                    jProgramsTable.scrollRectToVisible(jProgramsTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else{
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = programQuer.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);
                    }
                    programLlist.clear();
                    programLlist.addAll(data);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
       

    }//GEN-LAST:event_addButtonActionPerformed

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
   
        s=jProgramsTable.getSelectedRow();
        
            if (s>=0) {
                Program p = programLlist.get(jProgramsTable.convertRowIndexToModel(s));
                Collection<Card> cl = p.getCardCollection();
                if (cl.isEmpty()){
                        programLlist.remove(p);
                        em.remove(p);
                }
                    else {
                        String message = "Αδύνατη η διαγραφή. Το πρόγραμμα χρησιμοποιείται από τουλάχιστον έναν πελάτη.";
                        JOptionPane.showMessageDialog(this, message, "Προσοχή", 0);
                    }
                }
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
    
      s= jProgramsTable.getSelectedRow();
       
       if (s>=0) { 
        p = programLlist.get(s);
        EditProgramForm epf = new EditProgramForm(p,true);
        epf.setIconImage(Toolkit.getDefaultToolkit().getImage(Session.imgPath + "programmsIcon.png"));
        epf.setVisible(true);
        epf.setLocationRelativeTo(null); //center form   
        thisFrame=this;
        thisFrame.setEnabled(false);
///////////////////////////Start Listeners////////////////////////////////////// 
         epf.addWindowListener(new WindowListener() {
             public void windowClosed(WindowEvent arg0) {
                 System.out.println("Window close event occur");
                 if (((MyWindowEvent)arg0).exitAndSave){

                 //    em.merge(p);
                     programLlist.set(s,p);
                     jProgramsTable.setRowSelectionInterval(s, s);
                     jProgramsTable.scrollRectToVisible(jProgramsTable.getCellRect(s, 0, true));
                     thisFrame.setEnabled(true);
                 }
                 else{
                     thisFrame.setEnabled(true);
                     em.getTransaction().rollback();
                     em.getTransaction().begin();
                     java.util.Collection data = programQuer.getResultList();
                     for (Object entity : data) {
                         em.refresh(entity);
                     }
                     programLlist.clear();
                     programLlist.addAll(data);
                 }
             }
             public void windowActivated(WindowEvent arg0) {
                 System.out.println("Window Activated");
             }
             public void windowClosing(WindowEvent arg0) {
                 System.out.println("Window Closing");
             }
             public void windowDeactivated(WindowEvent arg0) {
                 System.out.println("Window Deactivated");
             }
             public void windowDeiconified(WindowEvent arg0) {
                 System.out.println("Window Deiconified");
             }
             public void windowIconified(WindowEvent arg0) {
                 System.out.println("Window Iconified");
             }
             public void windowOpened(WindowEvent arg0) {
                 System.out.println("Window Opened");
             }
         });
       }  
    }//GEN-LAST:event_editButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed

        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        em.getTransaction().commit();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_saveButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListProgramForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ListProgramForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTable jProgramsTable;
    private javax.swing.JScrollPane jScrollPane1;
    private java.util.List<Program> programLlist;
    private javax.persistence.Query programQuer;
    private javax.swing.JButton saveButton;
    private java.util.List<Station> stationList;
    private javax.persistence.Query stationQuery;
    private javax.persistence.Query vehicleCategoryQuery;
    private java.util.List<VehicleCategory> vehicleCategpryList;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    JFrame thisFrame;
    Program p;
    int s ;
}
